package com.self.smallma.myblogweb.web;


import com.self.smallma.myblogweb.entity.UserEntity;
import com.self.smallma.myblogweb.service.BlogService;
import com.self.smallma.myblogweb.service.CommentService;
import com.self.smallma.myblogweb.vo.CommnetVo;
import com.self.smallma.myblogweb.vo.DetailedBlogVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Description: 评论控制器
 */
@Controller
public class CommentShowController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private BlogService blogService;

    @Value("${comment.avatar}")
    private String avatar;

//    查询评论列表
    @GetMapping("/comments/{blogId}")
    public String find(@PathVariable Long blogId, Model model) {
      List<CommnetVo> comments =  commentService.listCommentByBlogId(blogId);
        model.addAttribute("comments", comments);
        return "blog :: commentList";
    }

//    新增评论
    @PostMapping("/comments")
    public String post(CommnetVo comment, HttpSession session,Model model) {
        Long blogId = comment.getBlogId();
        UserEntity user = (UserEntity) session.getAttribute("user");
        if (user!=null){
            if (user.getUserId()==1){
                //管理员
                comment.setAvatar(user.getAvatar());
                comment.setAdminComment(1);
            }else {
                //普通用户
                comment.setAvatar(user.getAvatar());
                comment.setAdminComment(0);
            }

        }else {
            //未登录
            return "admin/register";
        }
        if (comment.getParentComment().getCommentId()!=null){
            comment.setParentCommentId(comment.getParentComment().getCommentId());
        }
        commentService.saveToVo(comment);
        List<CommnetVo> comments = commentService.listCommentByBlogId(blogId);
        model.addAttribute("comments", comments);
        System.out.println("add-------------");
        comments.forEach(System.out::println);
        return "blog :: commentList";
    }

//    删除评论
    @GetMapping("/comment/{blogId}/{id}/delete")
    public String delete(@PathVariable Long blogId, @PathVariable Long id,
                          Model model){

        commentService.removeById(id);
        DetailedBlogVo detailedBlog = blogService.getDetailedBlog(blogId);
        List<CommnetVo> commnetVos = commentService.listCommentByBlogId(blogId);
        model.addAttribute("blog", detailedBlog);
        model.addAttribute("comments", commnetVos);
        return "blog";
    }

}